import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../model/book.dart';

class BookApiService {
  final Dio _dio = Dio(BaseOptions(
    baseUrl: 'https://your-api-server.com/api',
    connectTimeout: const Duration(seconds: 5),
    receiveTimeout: const Duration(seconds: 5),
  ));

  Future<List<Book>> fetchBooks() async {
    try {
      final response = await _dio.get('/books');
      return (response.data as List)
          .map((json) => Book.fromJson(json))
          .toList();
    } catch (e) {
      throw Exception('Failed to load books: $e');
    }
  }

  Future<Book> getBookByIsbn(String isbn) async {
    try {
      final response = await _dio.get('/books/$isbn');
      return Book.fromJson(response.data);
    } catch (e) {
      throw Exception('Failed to load book: $e');
    }
  }

  Future<Book> addBook(Book book) async {
    try {
      final response = await _dio.post(
        '/books',
        data: book.toJson(),
      );
      return Book.fromJson(response.data);
    } catch (e) {
      throw Exception('Failed to add book: $e');
    }
  }

  // 添加本地缓存功能
  Future<void> cacheBooks(List<Book> books) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(
      'cached_books',
      jsonEncode(books.map((b) => b.toJson()).toList()),
    );
  }

  Future<List<Book>> getCachedBooks() async {
    final prefs = await SharedPreferences.getInstance();
    final cachedData = prefs.getString('cached_books');
    if (cachedData != null) {
      return (jsonDecode(cachedData) as List)
          .map((json) => Book.fromJson(json))
          .toList();
    }
    return [];
  }
}